package com.example.mediaplayerdemo.main.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.mediaplayerdemo.R;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends Fragment implements ViewPager.OnPageChangeListener{

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private LinearLayout llPoint;
    private ViewPager vp;
    private TextView tvDesc;
    private int[] imageResIds; //存放图片资源id的数组
    private ArrayList<ImageView> imageViews; //存放图片的集合
    private String[] contentDescs; //图片内容描述
    private int lastPosition;
    private boolean isRunning = false; //viewpager是否在自动轮询

    public MainFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        initView(view);
        initData();
        initAdapter();
        new Thread() {
            @Override
            public void run() {
                isRunning = true;
                while (isRunning) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (isRunning) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                vp.setCurrentItem(vp.getCurrentItem() + 1);
                            }
                        });
                    }
                }
            }
        }.start();
        return view;
    }

    private void initView(View view) {
        llPoint = (LinearLayout) view.findViewById(R.id.llPoint);
        vp = (ViewPager) view.findViewById(R.id.vp);
    //        滚动监听
        vp.setOnPageChangeListener(this);
        tvDesc = (TextView) view.findViewById(R.id.tvDesc);
    }

    private void initData() {
        imageResIds = new int[]{R.mipmap.ic_launcher, R.mipmap.ic_launcher_round, R.mipmap.ic_launcher,
                R.mipmap.ic_launcher_round, R.mipmap.ic_launcher};
        contentDescs = new String[]{
                "厦门特大香烟走私犯外逃14年今被遣返",
                "“机器换人”大潮之下 那些普通工人在想什么？",
                "外媒关注中国\"最美野长城毁容\":文物保护观念落后",
                "男子涉嫌骗取公司1亿资金理财 潜逃境外8天被抓获",
                "国家南海博物馆完成封顶 打造中国南海地标式建筑"
        };
        imageViews = new ArrayList<>();
        ImageView imageView;
        View pointView;
        for (int i = 0; i < imageResIds.length; i++) {
            imageView = new ImageView(getContext());
            imageView.setBackgroundResource(imageResIds[i]);
            imageViews.add(imageView);

            pointView = new View(getContext());
            pointView.setBackgroundResource(R.drawable.radiobutton_off_background);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(25, 25);
            if (i != 0) {
                layoutParams.leftMargin = 10;
            }
            llPoint.addView(pointView, layoutParams);
        }
    }

    private void initAdapter() {
        llPoint.getChildAt(0).setBackgroundResource(R.drawable.radiobutton_on_background);
        tvDesc.setText(contentDescs[0]);
        lastPosition = 0;
        vp.setAdapter(new MyPagerAdapter());
        vp.setCurrentItem(5000000);
    }

    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            int newPosition = position % 5;
            ImageView imageView = imageViews.get(newPosition);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        int newPosition = position % 5;
        tvDesc.setText(contentDescs[newPosition]);
        llPoint.getChildAt(lastPosition).setBackgroundResource(R.drawable.radiobutton_off_background);
        llPoint.getChildAt(newPosition).setBackgroundResource(R.drawable.radiobutton_on_background);
        lastPosition = newPosition;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}